<template>
  <div>
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="员工管理" name="first">
        <div class="firstBox app-container">
          <el-form
            :model="firstQueryParams"
            ref="firstQueryRef"
            inline
            label-width="68px"
          >
            <el-form-item label="员工名称" prop="nickName">
              <el-input
                v-model="firstQueryParams.nickName"
                placeholder="请输入员工姓名"
                clearable
                style="width: 240px"
              ></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input
                v-model="firstQueryParams.mobile"
                placeholder="请输入手机号"
                clearable
                style="width: 240px"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleStaffQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetStaffQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Plus"
                v-hasPermi="['institution:staff:add']"
                @click="handleStaffAdd"
                >新增员工</el-button
              >
            </el-col>
          </el-row>
          <el-table v-loading="firstLoading" border :data="staffList">
            <!-- <el-table-column
              type="selection"
              width="55"
              align="center"
            ></el-table-column> -->
            <el-table-column label="序号" width="55" align="center">
              <template #default="scope">
                <span>{{
                  (firstQueryParams.pageNum - 1) * firstQueryParams.pageSize +
                  scope.$index +
                  1
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="员工姓名"
              align="center"
              prop="nickName"
            ></el-table-column>
            <el-table-column
              label="手机号"
              align="center"
              prop="mobile"
            ></el-table-column>
            <el-table-column
              label="性别"
              align="center"
              prop="gender"
              width="80"
            >
              <template #default="scope">
                <div>
                  {{
                    sys_user_sex.filter(
                      (val) => val.value == scope.row.gender
                    )[0].label
                  }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="是否授课"
              align="center"
              prop="isTeach"
              width="80"
            >
              <template #default="scope">
                <div>{{ scope.row.isTeach === true ? "是" : "否" }}</div>
              </template>
            </el-table-column>
            <el-table-column label="角色" align="center" width="500">
              <template #default="scope">
                <el-tag
                  class="ml10 mb10"
                  v-for="(item, index) in scope.row.roleNames &&
                  scope.row.roleNames.split(',')"
                  :key="index"
                  >{{ item }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="在职状态" align="center" width="100">
              <template #default="scope">
                <!-- <el-switch
                  v-model="scope.row.isJob"
                  :active-value="true"
                  :inactive-value="false"
                >
                </el-switch> -->
                <div>{{ scope.row.isJob === true ? "在职" : "离职" }}</div>
              </template>
            </el-table-column>
            <el-table-column
              label="备注"
              align="center"
              prop="remark"
            ></el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="300"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  v-hasPermi="['institution:staff:edit']"
                  @click="handleUpdateStaff(scope.row)"
                  >编辑</el-button
                >
                <!-- 校长角色不能删除 "214,215,3,4,5"-->
                <el-button
                  link
                  type="danger"
                  icon="Delete"
                  v-hasPermi="['institution:staff:delete']"
                  @click="handleDeleteStaff(scope.row)"
                  v-show="scope.row.isJob == false"
                  >删除</el-button
                >
                <el-button
                  link
                  type="primary"
                  icon="Warning"
                  @click="handleResignStaff(scope.row)"
                  v-hasPermi="['institution:staff:edit']"
                  v-show="scope.row.isJob == true"
                  >离职</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="firstTotal > 0"
            :total="firstTotal"
            v-model:page="firstQueryParams.pageNum"
            v-model:limit="firstQueryParams.pageSize"
            @pagination="getStaffList"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="角色管理" name="second">
        <div class="app-container">
          <el-form
            :model="secondQueryParams"
            ref="secondQueryRef"
            inline
            label-width="68px"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                v-model="secondQueryParams.roleName"
                placeholder="请输入角色名称"
                clearable
                style="width: 240px"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleRoleQuery"
                >搜索</el-button
              >
              <el-button icon="Refresh" @click="resetRoleQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <!-- 角色数据 -->
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleRoleAdd"
                v-hasPermi="['institution:role:add']"
                >新增角色</el-button
              >
            </el-col>
          </el-row>

          <el-table v-loading="secondLoading" border :data="roleDataList">
            <el-table-column label="序号" width="55" align="center">
              <template #default="scope">
                <span>{{
                  (secondQueryParams.pageNum - 1) * secondQueryParams.pageSize +
                  scope.$index +
                  1
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="角色名称"
              align="center"
              prop="roleName"
              width="300"
            ></el-table-column>
            <el-table-column
              width="160"
              label="类别"
              align="center"
              prop="orgId"
            >
              <template #default="scope">
                <el-tag>{{ scope.row.orgId == 1 ? "默认" : "自定义" }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="启用状态" align="center" width="100">
              <template #default="scope">
                <el-tag>{{ scope.row.status == 0 ? "正常" : "停用" }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="备注"
              align="center"
              prop="remark"
            ></el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="300"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdateRole(scope.row, '修改角色')"
                  v-show="scope.row.orgId != 1"
                  v-hasPermi="['institution:role:edit']"
                  >编辑</el-button
                >
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  v-show="scope.row.orgId != 1"
                  v-hasPermi="['institution:role:delete']"
                  @click="handleDeleteRole(scope.row)"
                  >删除</el-button
                >

                <el-button
                  link
                  type="primary"
                  icon="View"
                  @click="handleUpdateRole(scope.row, '查看角色')"
                  >查看</el-button
                >
                <el-button
                  link
                  type="primary"
                  icon="User"
                  @click="handleViewStaff(scope.row)"
                  >人员</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="secondTotal > 0"
            :total="secondTotal"
            v-model:page="secondQueryParams.pageNum"
            v-model:limit="secondQueryParams.pageSize"
            @pagination="getRoleDataList"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 新增员工 -->
    <el-drawer
      v-model="staffOpen"
      :title="staffTitle"
      :width-header="true"
      size="50%"
      :close-on-click-modal="false"
    >
      <div class="content">
        <el-form
          ref="staffFormRef"
          :model="staffForm"
          label-width="100px"
          label-suffix=" :"
        >
          <el-form-item
            label="登陆账号"
            prop="name"
            :rules="[
              {
                required: true,
                message: '请输入登陆账号',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="staffForm.name"
              placeholder="请输入登陆账号"
              style="width: 300px"
              clearable
            ></el-input
          ></el-form-item>
          <el-form-item
            label="员工姓名"
            prop="nickName"
            :rules="[
              {
                required: true,
                message: '请输入员工姓名',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="staffForm.nickName"
              placeholder="请输入员工姓名"
              style="width: 300px"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="mobile"
            :rules="[
              {
                required: true,
                message: '请输入正确得手机号',
                trigger: 'blur',
                pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              },
            ]"
          >
            <el-input
              v-model="staffForm.mobile"
              placeholder="请输入手机号"
              clearable
              style="width: 300px"
            ></el-input>
          </el-form-item>
          <el-form-item style="margin-top: -10px"
            ><div style="color: #aaa">
              此手机号将作为员工登录系统的账号，初始密码：123456
            </div></el-form-item
          >
          <el-form-item label="性别">
            <el-radio-group v-model="staffForm.gender">
              <el-radio
                v-for="dict in sys_user_sex"
                :key="dict.value"
                :value="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- <el-form-item label="是否在职" prop="isJob">
            <el-switch
              v-model="staffForm.isJob"
              :active-value="true"
              :inactive-value="false"
              @change="handleIsJobChange"
            ></el-switch>
          </el-form-item> -->
          <el-form-item label="是否授课" prop="isTeach">
            <el-switch
              v-model="staffForm.isTeach"
              :active-value="true"
              :inactive-value="false"
              @change="handleIsTeachChange"
            ></el-switch>
          </el-form-item>
          <el-form-item style="margin-top: -10px"
            ><div style="color: #aaa">
              开启后，该员工将出现在老师管理，可为该员工进行上课安排
            </div></el-form-item
          >
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="staffForm.remark"
              style="width: 300px"
              :rows="4"
              type="textarea"
              placeholder="请输入备注"
            />
          </el-form-item>
          <el-form-item label="所属角色">
            <div>选择角色后，下方将显示对应的权限。</div>
          </el-form-item>
          <el-form-item prop="roleIds">
            <div style="display: flex; flex-wrap: wrap">
              <div
                v-for="item in staffRoleList"
                :key="item.orgId"
                :class="[
                  'staffRoleItem',
                  selectRoles.indexOf(item.roleId) !== -1
                    ? 'selectStaffRole'
                    : '',
                ]"
                @click="handleChooseRole(item)"
              >
                <div style="display: flex; align-items: center">
                  <div
                    style="
                      background-color: #2f90ea;
                      text-align: center;
                      width: 30px;
                      height: 30px;
                      line-height: 30px;
                      border-radius: 15px;
                    "
                  >
                    <el-icon color="#fff" :size="16" style="margin-top: 6px">
                      <Avatar />
                    </el-icon>
                  </div>
                  <div
                    class="ml10"
                    style="
                      color: #333;
                      white-space: nowrap;
                      overflow: hidden;
                      text-overflow: ellipsis;
                    "
                  >
                    {{ item.roleName }}
                  </div>
                  <div class="customStyle" v-if="item.orgId != 1">自定义</div>
                </div>
                <div style="color: #999">{{ item.remark }}</div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="staffOpen = false">取消</el-button>
        <el-button type="primary" @click="submitStaffForm"> 保存 </el-button>
      </template>
    </el-drawer>
    <el-dialog tile="提示" v-model="isJobOpen" width="30%">
      <div style="display: flex; align-items: center">
        <el-icon :size="30" color="#e7a441"><WarningFilled /> </el-icon>
        <p style="margin-left: 10px; font-size: 18px">
          该员工有待跟进学员及学管师身份，请进行分配！
        </p>
      </div>
      <el-form
        ref="jobFormRef"
        :model="jobForm"
        label-width="100px"
        label-suffix=" :"
      >
        <el-form-item
          label="跟进人"
          prop="counselorId"
          :rules="[
            {
              required: true,
              message: '请选择跟进人',
              trigger: 'blur',
            },
          ]"
        >
          <el-select
            v-model="jobForm.counselorId"
            placeholder="请选择跟进人"
            clearable
          >
            <el-option
              v-for="item in counselors"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="学管师"
          prop="managementId"
          :rules="[
            {
              required: true,
              message: '请选择学管师',
              trigger: 'blur',
            },
          ]"
        >
          <el-select
            v-model="jobForm.managementId"
            placeholder="请选择学管师"
            clearable
          >
            <el-option
              v-for="item in managerArr"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="班级老师"
          prop="teacherId"
          :rules="[
            {
              required: true,
              message: '请选择班级老师',
              trigger: 'blur',
            },
          ]"
        >
          <el-select
            v-model="jobForm.teacherId"
            placeholder="请选择学管师"
            clearable
          >
            <el-option
              v-for="item in teacherArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="resignConfirm">确 定</el-button>
          <el-button @click="isJobOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增角色 -->
    <el-dialog :title="roleTitle" v-model="roleOpen" width="40%" append-to-body>
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        label-width="100px"
        label-suffix=" :"
        :disabled="roleTitle == '查看角色'"
      >
        <el-form-item
          label="角色名称"
          prop="roleName"
          :rules="[
            {
              required: true,
              message: '请输入角色名称',
              trigger: 'blur',
            },
          ]"
        >
          <el-input
            v-model="roleForm.roleName"
            placeholder="请输入角色名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="roleForm.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :value="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox
            v-model="menuExpand"
            @change="handleCheckedTreeExpand($event, 'menu')"
            >展开/折叠</el-checkbox
          >
          <el-checkbox
            v-model="menuNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'menu')"
            >全选/全不选</el-checkbox
          >
          <el-checkbox
            v-model="roleForm.menuCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'menu')"
            >父子联动</el-checkbox
          >
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menuRef"
            node-key="id"
            :check-strictly="!roleForm.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="roleForm.remark"
            type="textarea"
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            v-if="roleTitle != '查看角色'"
            @click="submitRoleForm"
            >确 定</el-button
          >
          <el-button @click="cancelRoleForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看人员列表 -->
    <el-dialog title="所属人员" v-model="viewStaffOpen" width="50%">
      <div class="app-container">
        <el-table border :data="viewStaffList">
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              <span>{{
                (viewStaffParams.pageNum - 1) * viewStaffParams.pageSize +
                scope.$index +
                1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="员工姓名"
            align="center"
            prop="nickName"
          ></el-table-column>
          <el-table-column
            label="手机号"
            align="center"
            prop="mobile"
          ></el-table-column>
          <el-table-column label="性别" align="center" prop="gender">
            <template #default="scope">
              <div>
                {{
                  sys_user_sex.filter((val) => val.value == scope.row.gender)[0]
                    .label
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="是否授课" align="center" prop="isTeach">
            <template #default="scope">
              <div>{{ scope.row.isTeach === true ? "是" : "否" }}</div>
            </template>
          </el-table-column>
          <el-table-column label="在职状态" align="center">
            <template #default="scope">
              <div>{{ scope.row.isJob === true ? "在职" : "离职" }}</div>
            </template>
          </el-table-column>
          <el-table-column
            label="备注"
            align="center"
            prop="remark"
          ></el-table-column>
        </el-table>
        <!-- <pagination
          v-show="viewStaffTotal > 0"
          :total="viewStaffTotal"
          v-model:page="viewStaffParams.pageNum"
          v-model:limit="viewStaffParams.pageSize"
          @pagination="getRoleDataList"
        /> -->
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewStaffOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="Staff">
import { onMounted, reactive, ref, toRefs, nextTick } from "vue";
import {
  getStaffApi,
  getStaffRolesApi,
  saveStaffApi,
  getStaffInfoApi,
  updateStaffApi,
  deleteStaffApi,
  getRoleDataListApi,
  getRoleUsersApi,
} from "@/api/institution/staff";
import {
  roleMenuTreeselect,
  treeselect as menuTreeselect,
} from "@/api/system/menu";
import {
  getFollowPeopleList,
  getManagerList,
  getPeopleList,
} from "@/api/studentManagement/index.js";
import { addRole, updateRole, getRole, delRole } from "@/api/system/role";
import { getLoginDeptAuth } from "@/utils/auth";

const { proxy } = getCurrentInstance();

const activeName = ref("first");
const firstLoading = ref(false);
const staffList = ref([]);
const firstTotal = ref(0);
// 新增员工弹窗
const staffOpen = ref(false);
const staffTitle = ref("新增员工");
const staffRoleList = ref([]); // 员工角色列表
const selectRoles = ref([]); // 选中角色集合

const isJobOpen = ref(false);
const counselors = ref([]); // 跟进人列表
const managerArr = ref([]); // 学管师列表
const teacherArr = ref([]); // 班级老师列表

// 角色列表集合
const roleDataList = ref([]);
const secondTotal = ref(0);
const secondLoading = ref(false);
const roleTitle = ref("新增角色");
const roleOpen = ref(false);
const menuOptions = ref([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const menuRef = ref(null);
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const { sys_user_sex } = proxy.useDict("sys_user_sex");

// 查看人员
const viewStaffOpen = ref(false);
const viewStaffList = ref([]);
const viewStaffTotal = ref(0);

const data = reactive({
  firstQueryParams: {
    nickName: undefined,
    mobile: undefined,
    pageNum: 1,
    pageSize: 10,
  },
  staffForm: {
    id: "",
    name: "", // 登陆账号
    nickName: "", // 员工姓名
    gender: "0", // 性别 0： 男， 1： 女
    mobile: "", // 手机号
    isTeach: false, // 是否授课
    isJob: true, // 在职
    remark: "", // 备注
    roleIds: "",
  },
  jobForm: {
    id: "", // 离职人id
    counselorId: "", // 跟进人
    managementId: "", // 学管师
    teacherId: "", // 班级老师
  },
  secondQueryParams: {
    roleName: "",
    pageNum: 1,
    pageSize: 10,
  },
  roleForm: {
    roleId: "",
    roleName: "",
    roleSort: 99,
    roleKey: `c_${getLoginDeptAuth()}_${new Date().getTime()}`,
    status: "0",
    menuIds: [],
    menuCheckStrictly: true,
    remark: "",
  },
  viewStaffParams: {
    pageNum: 1,
    pageSize: 99999,
  },
});

const {
  firstQueryParams,
  staffForm,
  jobForm,
  secondQueryParams,
  roleForm,
  viewStaffParams,
} = toRefs(data);

// 获取员工列表
const getStaffList = async () => {
  firstLoading.value = true;
  const { total, rows } = await getStaffApi(firstQueryParams.value);

  staffList.value = rows;
  firstTotal.value = total;
  firstLoading.value = false;
};

// 重置员工新增表单
const resetStaff = () => {
  staffForm.value = {
    id: "",
    name: "", // 登陆账号
    nickName: "", // 员工姓名
    gender: "0",
    mobile: "", // 手机号
    isJob: true, // 在职
    isTeach: false, // 是否授课
    remark: "", // 备注
    roleIds: "",
  };
  selectRoles.value = [];
  proxy.resetForm("staffFormRef");
};

// 员工搜索操作
const handleStaffQuery = () => {
  firstQueryParams.value.pageNum = 1;
  getStaffList();
};

// 员工重置操作
const resetStaffQuery = () => {
  proxy.resetForm("firstQueryRef");
  handleStaffQuery();
};

/** 员工新增 */
const handleStaffAdd = async () => {
  resetStaff();
  staffOpen.value = true;
  staffTitle.value = "新增员工";
};

// 修改员工
const handleUpdateStaff = (row) => {
  resetStaff();
  const userId = row.id;
  getStaffInfoApi(userId).then((res) => {
    staffOpen.value = true;
    staffTitle.value = "修改员工";
    staffForm.value = res.data;
    staffForm.value.gender = staffForm.value.gender.toString();
    selectRoles.value = res.roleIds;
  });
};

// 删除员工操作
const handleDeleteStaff = (row) => {
  const userId = row.id;
  proxy.$modal
    .confirm("是否确认删除?")
    .then(function () {
      return deleteStaffApi(userId);
    })
    .then(() => {
      getStaffList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

// 获取跟进人
const getFollowPeople = async () => {
  counselors.value = [];
  const { rows } = await getFollowPeopleList({ pageNum: 1, pageSize: 9999 });
  rows.forEach((item) => {
    if (item.isJob == true && item.id != jobForm.value.id) {
      counselors.value.push(item);
    }
  });
};

// 获取学管师
const getManagerDatas = async () => {
  managerArr.value = [];
  const { data } = await getManagerList({ pageNum: 1, pageSize: 9999 });
  data.forEach((item) => {
    if (item.isJob == true && item.id != jobForm.value.id) {
      managerArr.value.push(item);
    }
  });
};

// 获取班级老师
const getTeachers = async () => {
  teacherArr.value = [];

  const { data } = await getPeopleList({ isTeach: 1 });
  data.forEach((item) => {
    if (item.isJob == true && item.value != jobForm.value.id) {
      teacherArr.value.push(item);
    }
  });
};

// 员工离职
const handleResignStaff = async (row) => {
  jobForm.value.id = row.id;
  proxy.$modal
    .confirm("是否确认离职?")
    .then(async () => {
      const { data } = await updateStaffApi({
        id: jobForm.value.id,
        isJob: false,
      });
      if (data) {
        getStaffList();
        proxy.$modal.msgSuccess("操作成功");
      } else {
        isJobOpen.value = true;
        // resetJobForm();
        jobForm.value.counselorId = "";
        jobForm.value.managementId = "";
        jobForm.value.teacherId = "";
        // 获取跟进人
        await getFollowPeople();
        // 获取学管师
        await getManagerDatas();
        // 获取班级老师
        await getTeachers();
      }
    })
    .catch(() => {});
};

// 确定离职分配
const resignConfirm = () => {
  proxy.$refs["jobFormRef"].validate((valid) => {
    if (valid) {
      updateStaffApi({
        id: jobForm.value.id,
        isJob: false,
        convert: {
          counselorId: jobForm.value.counselorId,
          managementId: jobForm.value.managementId,
          teacherId: jobForm.value.teacherId,
        },
      }).then(async (res) => {
        //   const { data } = await updateStaffApi({
        //     id: jobForm.value.id,
        //     isJob: false,
        //   });
        //   if (data) {
        //   getStaffList();
        //   proxy.$modal.msgSuccess("操作成功");
        // }
        proxy.$modal.msgSuccess(res.msg);
        isJobOpen.value = false;
        getStaffList();
      });
    }
  });
};

const resetJobForm = () => {
  jobForm.value = {
    counselorId: "",
    managementId: "",
    teacherId: "",
  };
  // proxy.resetForm("jobFormRef");
};

// 获取员工角色列表
const getStaffRoles = async () => {
  const { roles } = await getStaffRolesApi();
  staffRoleList.value = roles;
};

// 员工新增选择角色
const handleChooseRole = async (item) => {
  if (selectRoles.value.indexOf(item.roleId) !== -1) {
    // 取消选中
    selectRoles.value = selectRoles.value.filter((val) => val !== item.roleId);
  } else {
    selectRoles.value.push(item.roleId);
  }
};

// 是否授课
const handleIsTeachChange = (value) => {
  staffForm.value.isTeach = value;
};

// 是否在职
const handleIsJobChange = (value) => {
  staffForm.value.isJob = value;
};

// 员工新增提交
const submitStaffForm = () => {
  proxy.$refs["staffFormRef"].validate((valid) => {
    if (valid) {
      if (staffForm.value.id != undefined && staffForm.value.id != "") {
        // 修改
        updateStaffApi({
          ...staffForm.value,
          roleIds: selectRoles.value.join(","),
        }).then((res) => {
          proxy.$modal.msgSuccess(res.msg);
          staffOpen.value = false;
          getStaffList();
        });
      } else {
        // 新增
        staffForm.value.roleIds = selectRoles.value.join(",");
        saveStaffApi(staffForm.value).then((res) => {
          proxy.$modal.msgSuccess(res.msg);
          staffOpen.value = false;
          getStaffList();
        });
      }
    }
  });
};

// 角色搜索
const handleRoleQuery = () => {
  secondQueryParams.value.pageNum = 1;
  getRoleDataList();
};

// 角色重置
const resetRoleQuery = () => {
  proxy.resetForm("secondQueryRef");
  handleRoleQuery();
};

// 新增角色
const handleRoleAdd = () => {
  resetRoleForm();
  getMenuTreeselect();
  roleOpen.value = true;
  roleTitle.value = "添加角色";
};

// 修改角色
const handleUpdateRole = (row, title) => {
  resetRoleForm();
  const roleId = row.roleId;
  const roleMenu = getRoleMenuTreeselect(roleId);
  getRole(roleId).then((res) => {
    roleForm.value = res.data;
    roleForm.value.roleSort = Number(roleForm.value.roleSort);
    roleOpen.value = true;
    nextTick(() => {
      roleMenu.then((res) => {
        let checkedKeys = res.checkedKeys;
        checkedKeys.forEach((v) => {
          nextTick(() => {
            menuRef.value.setChecked(v, true, false);
          });
        });
      });
    });
    roleTitle.value = title;
  });
};

/** 根据角色ID查询菜单树结构 */
function getRoleMenuTreeselect(roleId) {
  return roleMenuTreeselect(roleId).then((response) => {
    menuOptions.value = response.menus;
    return response;
  });
}

// 添加角色  获取菜单树
const getMenuTreeselect = () => {
  menuTreeselect().then((res) => {
    menuOptions.value = res.data;
  });
};

/** 树权限（展开/折叠） */
const handleCheckedTreeExpand = (value, type) => {
  if (type == "menu") {
    let treeList = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  } else if (type == "dept") {
    let treeList = deptOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
};

/** 树权限（全选/全不选） */
const handleCheckedTreeNodeAll = (value, type) => {
  if (type == "menu") {
    menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
  } else if (type == "dept") {
    deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
  }
};

/** 树权限（父子联动） */
const handleCheckedTreeConnect = (value, type) => {
  if (type == "menu") {
    roleForm.value.menuCheckStrictly = value ? true : false;
  } else if (type == "dept") {
    roleForm.value.deptCheckStrictly = value ? true : false;
  }
};

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

// 提交新增角色
const submitRoleForm = () => {
  proxy.$refs["roleFormRef"].validate((valid) => {
    if (valid) {
      if (roleForm.value.roleId != undefined && roleForm.value.roleId != "") {
        // 修改
        roleForm.value.menuIds = getMenuAllCheckedKeys();
        updateRole(roleForm.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          roleOpen.value = false;
          getRoleDataList();
        });
      } else {
        roleForm.value.menuIds = getMenuAllCheckedKeys();
        addRole(roleForm.value).then((res) => {
          proxy.$modal.msgSuccess("新增成功");
          roleOpen.value = false;
          getRoleDataList();
        });
      }
    }
  });
};

// 删除角色
const handleDeleteRole = (row) => {
  const roleIds = row.roleId;
  proxy.$modal
    .confirm("是否确认删除")
    .then(function () {
      return delRole(roleIds);
    })
    .then(() => {
      getRoleDataList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

const resetRoleForm = () => {
  roleForm.value = {
    roleId: "",
    roleName: "", // 登陆账号
    roleSort: 99, // 员工姓名
    roleKey: `c_${getLoginDeptAuth()}_${new Date().getTime()}`,
    status: "0",
    menuIds: [],
    menuCheckStrictly: true,
    remark: "",
  };
  proxy.resetForm("roleFormRef");
};

const cancelRoleForm = () => {
  roleOpen.value = false;
  resetRoleForm();
};

// 获取角色列表数据
const getRoleDataList = async () => {
  secondLoading.value = true;
  const { total, rows } = await getRoleDataListApi(secondQueryParams.value);
  roleDataList.value = rows;
  secondTotal.value = total;
  secondLoading.value = false;
};

// 查看人员列表
const handleViewStaff = async (row) => {
  const { total, rows } = await getRoleUsersApi({
    roleId: row.roleId,
    ...viewStaffParams.value,
  });
  viewStaffList.value = rows;
  viewStaffTotal.value = total;
  viewStaffOpen.value = true;
};

// tab切换
const handleTabClick = async (tab, event) => {
  if (tab.paneName == "first") {
    // 员工
    // 获取员工列表
    await getStaffList();
    await getStaffRoles();
  } else {
    // 角色
    // 获取角色列表数据
    await getRoleDataList();
  }
};

// 初始化请求
onMounted(async () => {
  // 获取员工列表
  await getStaffList();
  // 获取弹窗员工角色
  await getStaffRoles();
});
</script>
<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";
.staffRoleItem {
  width: 230px;
  height: 150px;
  border-radius: 10px;
  border: 1px solid #eee;
  margin-right: 20px;
  margin-bottom: 20px;
  padding: 15px;
  box-sizing: border-box;
  cursor: pointer;
}

.selectStaffRole {
  border-color: $--color-primary;
}

.customStyle {
  width: 50px;
  height: 24px;
  border-radius: 5px;
  line-height: 24px;
  border: 1px solid $--color-primary;
  text-align: center;
  font-size: 12px;
  margin-left: 10px;
}
</style>